package com.ebelter.seneo.ui.activitys;



import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;

import com.ebelter.btcomlib.CommonLib;
import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.bluetooth.base.BlueManager;
import com.ebelter.btcomlib.models.bluetooth.interfaces.IBlueStationListener;
import com.ebelter.btcomlib.models.bluetooth.products.scale.bean.ScaleMeasureResult;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserCurrentMeasureRecord;
import com.ebelter.btcomlib.models.db.products.seneo.SeneoUserinfos;
import com.ebelter.btcomlib.models.eventbus.CommonEventBus;
import com.ebelter.btcomlib.models.https.NetUtils;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponseSubInfo;
import com.ebelter.btcomlib.utils.StatusBarUtil;
import com.ebelter.btcomlib.utils.StringUtils;
import com.ebelter.btcomlib.utils.TimeUtils;
import com.ebelter.btcomlib.utils.ToastUtil;
import com.ebelter.btcomlib.utils.UserSpUtil;
import com.ebelter.btcomlib.utils.ViewUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.R;
import com.ebelter.seneo.beans.HostoryListData;
import com.ebelter.seneo.contants.IUserContant;
import com.ebelter.seneo.interfaces.SeneoBTI;
import com.ebelter.seneo.models.SeneoBTManager;
import com.ebelter.seneo.models.SeneoDbUtils;
import com.ebelter.seneo.models.SeneoNet;
import com.ebelter.seneo.models.UploadData2ServiceUtil;
import com.ebelter.seneo.models.googlefit.GoogleFitManager;
import com.ebelter.seneo.models.updateApp.UpdateService;
import com.ebelter.seneo.models.updateApp.Updater;
import com.ebelter.seneo.ui.activitys.sets.AboutActivity;
import com.ebelter.seneo.ui.fragments.main.Dash_Fragment;
import com.ebelter.seneo.ui.fragments.main.Goal_Fragment;
import com.ebelter.seneo.ui.fragments.main.Info_Fragment;
import com.ebelter.seneo.ui.fragments.main.Set_Fragment;
import com.ebelter.seneo.ui.fragments.main.Trend_Fragment;
import com.ebelter.seneo.ui.views.SeneoTipDialog1;
import com.ebelter.seneo.ui.views.SeneoTipDialog2;
import com.ebelter.seneo.utils.SeneoUtils;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;

public class SeneoMainActivity extends SeneoBaseActivity implements View.OnClickListener {

    public static final String TAG = "SeneoMainActivity";

    public static final String NEED_LOGIN = "NEED_LOGIN";

    public static final int RequestCode_BondDevice = 55;
    public static final int RequestCode_AddInfo = 56;


    public static void openSeneoMainActivity(Context context,boolean needLogin){
        Intent intent =new Intent(context,SeneoMainActivity.class);
        intent.putExtra(NEED_LOGIN,needLogin);
        context.startActivity(intent);
    }

    LinearLayout main_b_goal_ll;
    LinearLayout main_b_info_ll;
    LinearLayout main_b_dash_ll;
    LinearLayout main_b_trend_ll;
    LinearLayout main_b_set_ll;

    private int currentDisplayIndex;//0-4

    private Goal_Fragment mGoal_Fragment;
    private Info_Fragment mInfo_Fragment;
    private Dash_Fragment mDash_Fragment;
    private Trend_Fragment mTrend_Fragment;
    private Set_Fragment mSet_Fragment;


    private SeneoBTManager mSeneoBTManager;


    private Updater mUpdater;

    @Override
    protected int loadLayoutById() {
        return R.layout.activity_seneo_main;
    }


    @Override
    protected void initView() {
        EventBus.getDefault().register(this);


        boolean isLocServiceEnable=CommonLib.isLocServiceEnable(this);
        LogUtils.i(TAG,"----是否开启定位权限 isLocServiceEnable = " +isLocServiceEnable);

        mSeneoBTManager = new SeneoBTManager(this);
        mUpdater=new Updater();

        FV();
        displayFragment(2);
        setListeners();
    }

    @Override
    protected void initData() {

       // checkUpdate();

        boolean needLogin = getIntent().getBooleanExtra(NEED_LOGIN,true);
        if (needLogin){
            String loginName = UserSpUtil.readString(IUserContant.IUser.loginName);
            String loginPsw=UserSpUtil.readString(IUserContant.IUser.psw);
            String loginPsw2=UserSpUtil.readString(IUserContant.IUser.psw2);
            SeneoNet.getIntance().loginRequest(this, false, loginName,loginPsw , new HttpResponse<LoginResponseSubInfo>() {
                @Override
                public void result(boolean isRequestSuccess, String requestDes, LoginResponseSubInfo loginResponse,String s) {
                    // dissLoadingDialog();
                    LogUtils.i2(TAG,"----登录=loginResponse="+loginResponse);
                    // {resultData=null, responseStr='null', resultCode=-1, resultMessage='不存在的email或者昵称'}
                    if (isRequestSuccess){
                        if (loginResponse.resultCode==0){
                            //登录成功
                         //   ToastUtil.show("Login successfully!");
                            SeneoLoginActivity.saveUserDatas(loginResponse);
                            startWork();
                            return;
                        }
                    }
                    startActivity(new Intent(SeneoMainActivity.this,SeneoLoginActivity.class));
                    finish();
                }
            });
        }else {
            startWork();
        }


        openBluetoothTip();

    }

    private void openBluetoothTip() {
        if (!BlueManager.getInstance().isBluetoothOpen()){
            BlueManager.getInstance().openBluetooth3(this);
        }


    }

    private void checkUpdate() {

        if (NetUtils.available()){
            if(mUpdater==null){
                return;
            }
            mUpdater.checkVersion(this, new Updater.IGetVersion() {
                @Override
                public void callback(boolean needUpdate, UpdateVersionBean versionBean) {
                    if (needUpdate){
                        showUpdateDialog(versionBean);
                    }
                }
            });
        }
    }
    private void showUpdateDialog(final UpdateVersionBean versionBean){
        SeneoTipDialog2 tipDialog2=new SeneoTipDialog2(this,StringUtils.getResStr(R.string.New_version_is_available_touch_to_update));
        tipDialog2.setListener(new SeneoTipDialog2.ICancelOkBtListener() {
            @Override
            public void cancel(Dialog dialogView) {
                dialogView.cancel();
            }

            @Override
            public void ok(Dialog dialogView, String str) {
                if (!NetUtils.available()){
                    ToastUtil.show(R.string.Network_error);
                    return;
                }
                Intent updateIntent=new Intent(SeneoMainActivity.this,UpdateService.class);
                updateIntent.putExtra(UpdateService.DownloadSer,versionBean);
                SeneoMainActivity.this.startService(updateIntent);
                dialogView.cancel();

            }
        });
        tipDialog2.show();
    }

    private void startWork() {

        initGoogleFit();

        checkUpdate();
        //选取正确的用户信息
        long selectRightUserId = SeneoUtils.getCurrentUserUseId();//获取上一次的用户id
        SeneoUserinfos userinfos = SeneoDbUtils.getUserinfos(selectRightUserId);//查询一下用户是否存在
        if (userinfos==null){
            LogUtils.i(TAG,"----根据上一次登录的userid未找到相对应的用户信息 准备获取主人id");
            userinfos =SeneoDbUtils.getHostUserinfos();
            if (userinfos!=null){
                selectRightUserId=userinfos.user_id;
                LogUtils.i(TAG,"----找到了主人的信息作为用户信息下发 userinfos = "+userinfos);
            }else {
                LogUtils.i(TAG,"----XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX---------选择用户信息时 出现登录逻辑性的错误");
            }
            SeneoUtils.setCurrentUserUseId(selectRightUserId);
        }
        LogUtils.i(TAG,"-----userId使用的是 selectRightUserId = "+selectRightUserId);

        if(mSeneoBTManager!=null){
            mSeneoBTManager.setCurrentUserId(selectRightUserId);
            mSeneoBTManager.startWork();
        }

    }

    private void initGoogleFit() {
        GoogleFitManager googleFitManager=GoogleFitManager.getInstance();
        GoogleSignInAccount signInAccount = googleFitManager.getLastSignedInAccount(getApplicationContext());
        if (signInAccount==null) { //没有。则要登录
            //googleFitManager.signIn(this);
            LogUtils.i(TAG,"initGoogleFit--GoogleSignInAccount==null");
        }else{//有，则要订阅
           // SeneoUtils.setGoogleFitOpenFlag(true);
            LogUtils.i(TAG,"initGoogleFit--GoogleSignInAccount!=null 开始订阅");
            googleFitManager.sunbscrerib(this);
        }
    }

    public SeneoBTManager getSeneoBTManager(){
        return mSeneoBTManager;
    }

    private void FV() {
        main_b_goal_ll=findViewById(R.id.main_b_goal_ll);
        main_b_info_ll=findViewById(R.id.main_b_info_ll);
        main_b_dash_ll=findViewById(R.id.main_b_dash_ll);
        main_b_trend_ll=findViewById(R.id.main_b_trend_ll);
        main_b_set_ll=findViewById(R.id.main_b_set_ll);
    }



    public void restartSendUserInfo(int resistance,float weight){
        if (mSeneoBTManager!=null){
            LogUtils.i(TAG2,"----重新下发了用户信息 ---resistance="+resistance+"---weight="+weight);
            mSeneoBTManager.restartSendUserInfo(resistance,weight);
        }
    }

    public static boolean isResum;
    private void setListeners() {
        main_b_goal_ll.setOnClickListener(this);
        main_b_info_ll.setOnClickListener(this);
        main_b_dash_ll.setOnClickListener(this);
        main_b_trend_ll.setOnClickListener(this);
        main_b_set_ll.setOnClickListener(this);



        //设置回调监听器
        mSeneoBTManager.setmSeneoBTI(new SeneoBTI() {
            @Override
            public void showBondDialog() {
                //绑定设备的对话框
                LogUtils.i(TAG2,"----showBondDialog");
                showBandDialog();
            }

            @Override
            public void addInfoDialog(long userId, String nickname) {
                   //检测到用户信息不完全，弹出补全信息的对话框
                LogUtils.i(TAG2,"----addInfoDialog userId="+userId+"--nickname = "+nickname);
                showAddInfoDialog(userId,nickname);
            }

            @Override
            public void onReceiveMeasureResult(ScaleMeasureResult scaleMeasureResult) {
                //接收到数据
                LogUtils.i(TAG2,"----接收到测量结果 result = "+scaleMeasureResult);
                if (mDash_Fragment!=null){
                    mDash_Fragment.onReceiveMeasureResult(scaleMeasureResult);
                }
            }
            @Override
            public void onReceivedynamicMeasureResult(ScaleMeasureResult result) {
                LogUtils.i(TAG2,"----接收到动态测量结果 result = "+result);
                if (mDash_Fragment!=null){
                    mDash_Fragment.onReceivedynamicMeasureResult(result);
                }
            }

            @Override
            public void onWeightOverLoad() {
                //提示超重提示
                LogUtils.i(TAG2,"----超重");
                ToastUtil.show(R.string.chychzh);
            }

            @Override
            public void onReceiveHistoryRecord(ScaleMeasureResult scaleHisMeasureResult) {
                //接收到历史数据
                LogUtils.i(TAG2,"----接收到历史数据 "+scaleHisMeasureResult);
                if (mDash_Fragment!=null){
                    mDash_Fragment.onReceiveHistoryRecord(scaleHisMeasureResult);
                }
            }



            @Override
            public void onFatMeasureError(int type) {
                //测脂出错
                LogUtils.i(TAG2,"----测脂出错 type = " + type);
                if (isResum){
                    ToastUtil.show("Fat measurement error. Please stand uprightly on the scale barefoot and try again.");
                }
            }

            @Override
            public void onHistoryDownloadDone() {
                //历史数据接收完成
                LogUtils.i(TAG2,"----历史数据接收完成");
            }

            @Override
            public void unitChange(String unit) {
                //单位切换成功
                LogUtils.i(TAG2,"----单位切换成功");
            }

            @Override
            public void onLowPower() {
                //电量低提示
                LogUtils.i(TAG2,"----电量低提示");
                ToastUtil.show("Low power, please replace the batteries.");
            }

            @Override
            public void setUserInfoSuccess() {
                LogUtils.i(TAG2,"----下发用户信息成功");
            }

            @Override
            public void receiveTime(long time) {
                LogUtils.i(TAG2,"接收到体脂秤时间 = "+ TimeUtils.formatTime1(time));
            }

            @Override
            public void onScaleWake() {
                LogUtils.i(TAG2,"----秤--亮屏");
            }

            @Override
            public void onScaleSleep() {
                LogUtils.i(TAG2,"----秤--息屏");
            }

            @Override
            public void error(String msg) {
                LogUtils.i(TAG2,"----收到秤的错误信息"+msg);
            }

            @Override
            public void onConnected(BluetoothDevice device) {
                LogUtils.i(TAG2,"----秤--连接成功");
                setConnectFlagIV(true);
            }

            @Override
            public void onConnecting(BluetoothDevice device) {
                LogUtils.i(TAG2,"----秤--正在连接ing");
            }

            @Override
            public void onDisConnected() {
                LogUtils.i(TAG2,"----秤--连接断开");
                setConnectFlagIV(false);
            }
        });

        BlueManager.getInstance().addBluetoothStationListener(mIBlueStationListener);
    }

    private IBlueStationListener mIBlueStationListener = new IBlueStationListener() {
        @Override
        public void STATE_OFF() {

            ToastUtil.show(openBttip);
        }

        @Override
        public void STATE_TURNING_OFF() {

        }

        @Override
        public void STATE_ON() {


        }

        @Override
        public void STATE_TURNING_ON() {

        }
    };

    private static final String openBttip="This device has not enabled Bluetooth.Please enable in Settings";
    @Override
    protected void onResume() {
        super.onResume();
        isResum=true;
        if (!BlueManager.getInstance().isBluetoothOpen()){
            ToastUtil.show(openBttip);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isResum=false;
    }

    private void setConnectFlagIV(boolean isConnected){
        if (mDash_Fragment!=null)mDash_Fragment.setConnectFlagIV(isConnected);
    }



    public static final int white = Color.parseColor("#ffffffff");
    private static final int blue = Color.parseColor("#FF24CFFD");
    private void displayFragment(int currentDisplayIndex) {

        if (this.currentDisplayIndex==currentDisplayIndex){
            return;
        }
        this.currentDisplayIndex=currentDisplayIndex;

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        hideAllFragment(transaction, mGoal_Fragment, mInfo_Fragment,mDash_Fragment,mTrend_Fragment,mSet_Fragment);//隐藏全部的fragment

        ViewUtils.setSelects(false,main_b_goal_ll,main_b_info_ll,main_b_dash_ll,main_b_trend_ll,main_b_set_ll);
        int contain = R.id.main_container;
        if (currentDisplayIndex==0){
            ViewUtils.setSelect(main_b_goal_ll,true);
            if (mGoal_Fragment == null) {
                mGoal_Fragment = new Goal_Fragment();
                transaction.add(contain, mGoal_Fragment);
            } else {
                transaction.show(mGoal_Fragment);
            }
            StatusBarUtil.setColor(this,white,0);
            StatusBarUtil.setDarkStatusIcon(this,true);

        }else if (currentDisplayIndex==1){
            ViewUtils.setSelect(main_b_info_ll,true);
            if (mInfo_Fragment == null) {
                mInfo_Fragment = new Info_Fragment();
                transaction.add(contain, mInfo_Fragment);
            } else {
                transaction.show(mInfo_Fragment);
            }
            StatusBarUtil.setColor(this,white,0);
            StatusBarUtil.setDarkStatusIcon(this,true);
        }else if (currentDisplayIndex==2){
            ViewUtils.setSelect(main_b_dash_ll,true);
            if (mDash_Fragment == null) {
                mDash_Fragment = new Dash_Fragment();
                transaction.add(contain, mDash_Fragment);
            } else {
                transaction.show(mDash_Fragment);
            }
            StatusBarUtil.setColor(this,blue,0);
            StatusBarUtil.setDarkStatusIcon(this,false);

        }else if (currentDisplayIndex==3){
            ViewUtils.setSelect(main_b_trend_ll,true);
            if (mTrend_Fragment == null) {
                mTrend_Fragment = new Trend_Fragment();
                transaction.add(contain, mTrend_Fragment);
            } else {
                transaction.show(mTrend_Fragment);
            }
            StatusBarUtil.setColor(this,white,0);
            StatusBarUtil.setDarkStatusIcon(this,true);
        }else if (currentDisplayIndex==4){
            ViewUtils.setSelect(main_b_set_ll,true);
            if (mSet_Fragment == null) {
                mSet_Fragment = new Set_Fragment();
                transaction.add(contain, mSet_Fragment);
            } else {
                transaction.show(mSet_Fragment);
            }
            StatusBarUtil.setColor(this,white,0);
            StatusBarUtil.setDarkStatusIcon(this,true);
        }
        transaction.commitAllowingStateLoss();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_b_goal_ll:
                displayFragment(0);
                if(mGoal_Fragment!=null)mGoal_Fragment.updateUI();
                break;
            case R.id.main_b_info_ll:
                displayFragment(1);
                break;
            case R.id.main_b_dash_ll:
                displayFragment(2);
                break;
            case R.id.main_b_trend_ll:
                displayFragment(3);
                break;
            case R.id.main_b_set_ll:
                displayFragment(4);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mSeneoBTManager!=null){
            mSeneoBTManager.exit();
            mSeneoBTManager=null;
        }
        EventBus.getDefault().unregister(this);
        BlueManager.getInstance().addBluetoothStationListener(mIBlueStationListener);
    }

    SeneoTipDialog1 bandDeviceTipDialog1;
    //提示绑定对话框
    private void showBandDialog() {
        if (isFinishing()||isDestroyed()){
            return;
        }
        if (bandDeviceTipDialog1==null){
            bandDeviceTipDialog1=new SeneoTipDialog1(this,"Your device is not paired yet.");
            bandDeviceTipDialog1.setListener(new SeneoTipDialog1.IOkBtListener() {
                @Override
                public void ok(Dialog dialogView, Object object) {
                    Intent intent=new Intent(SeneoMainActivity.this,SeneoBondDeviceActivity.class);
                    startActivityForResult(intent,RequestCode_BondDevice);
                }
            });
            bandDeviceTipDialog1.setBtStr("Pair Now");
        }
       if (!bandDeviceTipDialog1.isShowing()){
           bandDeviceTipDialog1.show();
       }
    }

    private void cancleBandDialog() {
        if (bandDeviceTipDialog1!=null){
            bandDeviceTipDialog1.cancel();
            bandDeviceTipDialog1=null;
        }
    }

    SeneoTipDialog1 addInfoDialog;
    private void showAddInfoDialog(final long userId, final String nickname) {
        if (isFinishing()||isDestroyed()){
            return;
        }
        if (addInfoDialog==null){
            addInfoDialog=new SeneoTipDialog1(this,"Please complete the information first");
            addInfoDialog.setListener(new SeneoTipDialog1.IOkBtListener() {
                @Override
                public void ok(Dialog dialogView, Object object) {
                    SeneoAddInfoActivity.openSeneoAddInfoActivity(SeneoMainActivity.this,RequestCode_AddInfo,
                            SeneoAddInfoActivity.CMD_addinfo,nickname,userId);
                }
            });
            addInfoDialog.setBtStr(StringUtils.getResStr(R.string.tipdialog_sure));
        }
        if (!addInfoDialog.isShowing()){
            addInfoDialog.show();
        }
    }

    private void cancleAddinfoDialog() {
        if (addInfoDialog!=null){
            addInfoDialog.cancel();
            addInfoDialog=null;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CommonEventBus event) {
        if (!TextUtils.equals(event.whichReceive, TAG)) {
            return;
        }
        LogUtils.i(TAG, "SeneoMainActivity--onEventMainThread接收到CommonEventBus信息--" + event.toString());

        if (event.cmd== IUserContant.ICMDS.UNBOND_DEVICE_SUCCESS){
            LogUtils.i(TAG, "ICMDS - 解绑设备成功");
            if (mSeneoBTManager!=null){
                mSeneoBTManager.restartCheck();
            }
        }else if (event.cmd==IUserContant.ICMDS.SWITCH_USER){
            long userid = (long) event.getContent();
            LogUtils.i(TAG, "切换用户 userid = "+userid);
            if (mSeneoBTManager!=null){
                SeneoUtils.setCurrentUserUseId(userid);
                mSeneoBTManager.setCurrentUserId(userid);
                mSeneoBTManager.restartCheck();
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    displayFragment(2);
                }
            },500);
        }else if (event.cmd==IUserContant.ICMDS.UPDATA_CURRENT_USER_MEASURE_DATA){
            LogUtils.i(TAG, "更新当前用户最新的测量信息");
            HostoryListData.ResultDataBean.DataBean newdata = (HostoryListData.ResultDataBean.DataBean) event.content;
            UPDATA_CURRENT_USER_MEASURE_DATA(newdata);
        }else if (event.cmd==IUserContant.ICMDS.USER_INFO_CHANGE&&mSeneoBTManager!=null){
            long userid= (long) event.getContent();
            long currentUseUserId=mSeneoBTManager.getCurrentUserId();
            LogUtils.i(TAG, "ICMDS - 用户信息数据变更了 更新的userid="+userid+"---正在使用的currentUseUserId="+currentUseUserId);
            if (userid==currentUseUserId){
                mSeneoBTManager.setCurrentUserId(userid);
            }




        }

    }

    private void UPDATA_CURRENT_USER_MEASURE_DATA(HostoryListData.ResultDataBean.DataBean newdata) {
        LogUtils.i2(TAG, "更新当前用户信息及测量 newdata-->"+newdata);

        if (mSeneoBTManager!=null){
            SeneoUserinfos userinfos = mSeneoBTManager.getCurrentUserinfos();

            SeneoUserCurrentMeasureRecord seneoUserCurrentMeasureRecord = null;

            if (userinfos!=null){
                seneoUserCurrentMeasureRecord = SeneoDbUtils.getSeneoUserCurrentMeasureRecord(userinfos.host_id,userinfos.user_id);
            }

                if (newdata==null){
                    //说明没有最新数据了
                    if (userinfos!=null){
                        userinfos.currentWeight=0;//说明没有最新数据了,当前用户的体重值更新为0
                        updateUserWeight(userinfos.user_id,userinfos.currentWeight);
                        userinfos.update();
                    }
                    if (seneoUserCurrentMeasureRecord!=null){//说明没有最新数据了 把最新的一条删除掉
                        seneoUserCurrentMeasureRecord.delete();
                    }

                    if (mDash_Fragment!=null){
                        mDash_Fragment.setDisplayNullMeasure();
                    }


                }else {
                    //说明还有最新的数据
                    if (userinfos!=null){
                        userinfos.currentWeight= (float) newdata.getWeight();
                        updateUserWeight(userinfos.user_id,userinfos.currentWeight);
                        userinfos.update();
                    }

                    if (seneoUserCurrentMeasureRecord!=null){//说明有最新数据了 把最新的一条更新
                        seneoUserCurrentMeasureRecord.weight= (float) newdata.getWeight();
                        seneoUserCurrentMeasureRecord.fat= (float) newdata.getAdiposeRate();
                        seneoUserCurrentMeasureRecord.visceralFat= (float) newdata.getVisceralFat();
                        seneoUserCurrentMeasureRecord.bodyScore= (float) newdata.getBodySocre();
                        seneoUserCurrentMeasureRecord.bodyAge= (float) newdata.getPhysicalAge();
                        seneoUserCurrentMeasureRecord.skeletalMuscle= (float) newdata.getBoneMineralContent();
                        seneoUserCurrentMeasureRecord.waterRate= (float) newdata.getMoisture();
                        seneoUserCurrentMeasureRecord.protein= (float) newdata.getProtein();
                        seneoUserCurrentMeasureRecord.boneVolume= (float) newdata.getBoneMass();
                        seneoUserCurrentMeasureRecord.muscleVolume= (float) newdata.getMuscleQuantity();
                        seneoUserCurrentMeasureRecord.bmi= (float) newdata.getBmi();
                        seneoUserCurrentMeasureRecord.bmr= (float) newdata.getBmr();
                        seneoUserCurrentMeasureRecord.measureTime= newdata.getTestDate();
                        seneoUserCurrentMeasureRecord.weightControl= (float) newdata.getWeight();
                        seneoUserCurrentMeasureRecord.size= newdata.getSize();
                        seneoUserCurrentMeasureRecord.measureTime=newdata.getTestDate();
                        seneoUserCurrentMeasureRecord.update();
                    }

                }
            SeneoUtils.updateCurrentInfoDiaplay(TAG);
            SeneoUtils.sendCommonEventBus(TAG,Dash_Fragment.TAG,IUserContant.ICMDS.DISPLAY_DASH_USER_DATA,"显示最后测量的信息");
        }

    }

    //更新服务器上面的体重
    private void updateUserWeight(long userid,float currentWeight) {
        LogUtils.i2(TAG,"更新用户体重信息 userid = "+userid+"---currentWeight="+currentWeight);
        final Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("userId", userid);
        paramMap.put("weight", currentWeight);

        SeneoNet.getIntance().updateInfo(this, paramMap, new HttpResponse<BaseResponse>() {
            @Override
            public void result(boolean isRequestSuccess, String requestDes, BaseResponse baseResponse, String s) {
                LogUtils.i2(TAG,"更新用户体重信息 s = "+s);

                if (isRequestSuccess&&baseResponse!=null){

                    if (baseResponse.resultCode==0){//更新成功
                        LogUtils.i2(TAG,"更新用户体重信息 成功");
                    }else {
                        LogUtils.i2(TAG,"更新用户体重信息 失败");
                    }
                }else {
                    //更新失败
                    LogUtils.i2(TAG,"更新用户体重信息 失败");
                }
            }
        });
    }

    private android.os.Handler handler=new android.os.Handler();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==RequestCode_BondDevice){
            LogUtils.i(TAG2,"----onActivityResult--绑定界面刚出来");
            cancleBandDialog();
            if (mSeneoBTManager!=null)mSeneoBTManager.restartCheck();

        }else if (requestCode==RequestCode_AddInfo){
            LogUtils.i(TAG2,"----onActivityResult--添加信息界面刚出来 resultCode="+resultCode);
            if (resultCode==RESULT_OK){
                //说明添加信息成功
                LogUtils.i(TAG2,"----onActivityResult--添加用户信息成功--重新检测运行");
                cancleAddinfoDialog();
                if (mSeneoBTManager!=null)mSeneoBTManager.restartCheck();
            }else {
                LogUtils.i(TAG2,"----onActivityResult--添加用户信息失败");
            }

        }else if (requestCode==GuestSelectActivity.REQUEST_CODE&&resultCode==GuestSelectActivity.RESULT_CODE){

            long selectId =data.getLongExtra(GuestSelectActivity.SELECT_USERID,0);
            SeneoUtils.setCurrentUserUseId(selectId);

            LogUtils.i2(TAG2,"----onActivityResult--选择用户界面刚出来 selectId="+selectId);
            if (mSeneoBTManager!=null){
                mSeneoBTManager.setCurrentUserId(selectId);
                mSeneoBTManager.restartCheck();
            }



        }
    }


    @Override
    protected boolean isOpenBlueStationListener() {
        return true;
    }

    @Override
    public boolean isOpenTimeChangeListener() {
        return true;
    }

    /**
     public static final int NETWORK_NONE = -1;
     public static final int NETWORK_MOBILE = 0;
     public static final int NETWORK_WIFI = 1;
     */
    @Override
    protected void netStationChange(int netWorkState) {

    }

    /**
     * 0分钟变化 1日期变化
     */
    @Override
    protected void timeChange(int which) {
        updateDateTime();
    }
    public void updateDateTime(){
        if (mDash_Fragment!=null){
            mDash_Fragment.updateDateTime();
        }
    }


    public void mainStartActivityForResult(String openWhichTAG){
        if (GuestSelectActivity.TAG.equals(openWhichTAG)){//准备跳转
            startActivityForResult(new Intent(this,GuestSelectActivity.class),GuestSelectActivity.REQUEST_CODE);
        }
    }

    private long firstBackTime;
    @Override
    public void onBackPressed() {
       // super.onBackPressed();
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstBackTime > 2000) {
            ToastUtil.show(R.string.Touch_again_to_exit);
            firstBackTime = secondTime;
        } else {
            System.exit(0);
        }

    }
}
